package com.example.studentknowledge.repository;

import com.example.studentknowledge.entity.Article;
import com.example.studentknowledge.entity.Comment;
import com.example.studentknowledge.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 评论Repository接口
 */
@Repository
public interface CommentRepository extends JpaRepository<Comment, Long> {
    
    /**
     * 根据文章查找评论
     */
    Page<Comment> findByArticleOrderByCreatedAtDesc(Article article, Pageable pageable);
    
    /**
     * 根据用户查找评论
     */
    Page<Comment> findByUserOrderByCreatedAtDesc(User user, Pageable pageable);
    
    /**
     * 根据文章查找顶级评论（非回复）
     */
    @Query("SELECT c FROM Comment c WHERE c.article = :article AND c.parent IS NULL ORDER BY c.createdAt DESC")
    List<Comment> findTopLevelCommentsByArticle(@Param("article") Article article);
    
    /**
     * 根据父评论查找回复
     */
    List<Comment> findByParentOrderByCreatedAtAsc(Comment parent);
    
    /**
     * 统计文章的评论数
     */
    @Query("SELECT COUNT(c) FROM Comment c WHERE c.article = :article")
    Long countByArticle(@Param("article") Article article);
    
    /**
     * 统计用户的评论数
     */
    @Query("SELECT COUNT(c) FROM Comment c WHERE c.user = :user")
    Long countByUser(@Param("user") User user);
    
    /**
     * 获取最新评论
     */
    @Query("SELECT c FROM Comment c ORDER BY c.createdAt DESC")
    List<Comment> findLatestComments(Pageable pageable);
    
    /**
     * 根据内容模糊查询评论
     */
    @Query("SELECT c FROM Comment c WHERE c.content LIKE %:keyword% ORDER BY c.createdAt DESC")
    Page<Comment> findByContentContaining(@Param("keyword") String keyword, Pageable pageable);
}